import axios from "axios"
import { Message } from "element-ui"
import router from "@/router"
import Nprogress from "nprogress"

// 引入环境
import envConfig from './env'

// 创建axios
const service = axios.create({
    baseURL: envConfig.prodEnv.baseURL,
    timeout: 5000
})

// 设置请求拦截器
service.interceptors.request.use(config => {
    Nprogress.start()
    console.log('请求拦截', config);
    if (config.url !== '/login') {
        const token = sessionStorage.getItem("token")
        token && (config.headers['Authorization'] = token)
    }

    return config
}, error => { })


// 请求响应拦截器
service.interceptors.response.use(res => {
    Nprogress.done()
    console.log('响应拦截器', res);
    const { meta: { msg, status } } = res.data
    const arr = [200, 201, 204]
    if (arr.includes(status)) {
        const { data } = res.data
        if (res.config.url === '/login') {
            sessionStorage.setItem("token", data.token)
            router.push("/home")
        }
        Message({
            message: msg,
            type: 'success'
        });
        return data
    }
    Message({
        message: msg,
        type: 'error'
    });
    if (msg === "无效token") {
        router.push("/login")
    }
    return Promise.reject(msg)
})
export default service